package com.google.code.irouter.batch;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.code.irouter.model.History;
import com.google.code.irouter.model.Model;
import com.google.code.irouter.utils.DateTimeUtil;
import com.google.code.irouter.utils.ModelUtil;

public final class Scaner {

	public static void execute() {
		Date today = DateTimeUtil.getNow();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(today);
		calendar.add(Calendar.DATE, -10);
		Date targetDay = calendar.getTime();
		
		Query query = new Query(History.class.getSimpleName());
		query.addFilter("createDate", Query.FilterOperator.LESS_THAN_OR_EQUAL, targetDay);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		PreparedQuery preparedQuery = datastore.prepare(query);
		Iterator<Entity> entityIterator = preparedQuery.asIterator();

		List<Key> keyList = new ArrayList<Key>();
		while(entityIterator.hasNext()) {
			Entity entity = entityIterator.next();
			try {
				Model model = History.class.newInstance();
				if(model.parse(entity)) {
					keyList.add(entity.getKey());					
				}
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		
		if(keyList.size() > 0)
			ModelUtil.remove(keyList);
	}

}
